<template>
  <div>
    <el-main>
      <div class="box">
        <div class="top">
          <el-form
            :inline="true"
            :model="queryForm"
            class="demo-form-inline"
            style="float: left"
            size="medium"
          >
            <el-form-item label="旗区名称">
              <el-select
                v-model="selectedXzqh"
                placeholder="请选择旗区"
                @change="onXzqhChange"
              >
                <el-option
                  v-for="item in xzqhOptions"
                  :key="item.xzqhcode"
                  :label="item.xzqhname"
                  :value="item.xzqhcode"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="时间(年-月)：">
              <el-date-picker
                v-model="queryForm.yearMonth"
                type="month"
                placeholder="选择月"
                style="width: 160px"
                :default-value="currentDate"
                @change="onDateChange"
                :clearable="false"
              />
            </el-form-item>

            <el-form-item label="断面名称：">
              <el-input v-model="queryForm.keyword" placeholder="断面名称" />
            </el-form-item>
            <el-form-item label="数据状态">
              <el-select
                v-model="selectedStatus"
                placeholder="请选择数据状态"
                @change="fetchDataByStatus"
              >
                <el-option
                  v-for="(value, key) in config.shenhezt"
                  :key="key"
                  :label="value.status"
                  :value="key"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleOneKeyAudit"
                >一键审核</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="danger" @click="handleOneKeyRollback"
                >一键回退</el-button
              >
            </el-form-item>
          </el-form>
          <div
            style="
              float: right;
              margin-right: 60px;
              display: flex;
              align-items: center;
            "
          ></div>
        </div>
        <div class="center">
          <el-table
            :data="paginatedData"
            border
            style="width: 100%"
            size="medium"
            :max-height="tableheight"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              prop="dmmc"
              label="断面名称"
              show-overflow-tooltip
            />
            <el-table-column
              prop="liuyu"
              label="所在流域"
              show-overflow-tooltip
            />

            <el-table-column
              prop="xzqhname"
              label="行政区划"
              show-overflow-tooltip
            />
            <el-table-column
              prop="szmb"
              label="水质目标"
              show-overflow-tooltip
            />
            <el-table-column
              prop="szlb"
              label="水质类别"
              show-overflow-tooltip
            />

            <el-table-column
              prop="dmlaiyuan"
              label="断面类型"
              show-overflow-tooltip
            />

            <!-- <el-table-column prop="shenhezt" label="数据状态">
              <template slot-scope="scope">
                <el-tag :type="getTagType(scope.row.shenhezt)" size="small">{{
                  getStatusText(scope.row.shenhezt)
                }}</el-tag>
              </template>
            </el-table-column> -->

            <el-table-column prop="shenhezt" label="数据状态">
              <template slot-scope="scope">
                <el-tag
                  :type="config.shenhezt[scope.row.shenhezt].color"
                  size="small"
                >
                  {{ config.shenhezt[scope.row.shenhezt].status }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column
              prop="action"
              label="操作"
              width="170"
              align="center"
            >
              <template slot-scope="scope">
                <!-- 根据状态显示不同的按钮 -->
                <!-- 根据状态显示不同的按钮 -->
                <el-button
                  v-if="scope.row.shenhezt === '00'"
                  :type="config.shenhezt['00'].color"
                  size="mini"
                  disabled
                >
                  审核
                </el-button>
                <el-button
                  v-if="scope.row.shenhezt === '01'"
                  :type="config.shenhezt['01'].color"
                  size="mini"
                  disabled
                >
                  审核
                </el-button>
                <el-button
                  v-else-if="scope.row.shenhezt === '02'"
                  :type="config.shenhezt['02'].color"
                  size="mini"
                  @click="handleAudit(scope.row.dmszjcid)"
                >
                  审核
                </el-button>
                <!-- <el-button
                  v-else-if="scope.row.shenhezt === '02'"
                  :type="config.shenhezt['02'].color"
                  size="mini"
                  @click="handleAudit(scope.row.dmszjcid)"
                >
                  等待盟市审核
                </el-button> -->
                <el-button
                  v-else-if="scope.row.shenhezt === '03'"
                  :type="config.shenhezt['03'].color"
                  size="mini"
                  @click="handleView(scope.row.dmszjcid)"
                >
                  查看
                </el-button>
                <el-button
                  v-else-if="scope.row.shenhezt === '04'"
                  :type="config.shenhezt['04'].color"
                  size="mini"
                  @click="handleView(scope.row.dmszjcid)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 弹出框内容 -->
        <el-dialog
          title="审核"
          :visible.sync="dialogVisible"
          width="620"
          :destroy-on-close="true"
          :center="true"
        >
          <el-descriptions size="small" border>
            <!-- 描述项 -->
            <el-descriptions-item label="断面名称" :span="3">
              {{ dialogData.dmmc }}
            </el-descriptions-item>
            <el-descriptions-item label="日期" :span="2">
              {{ formatTimestamp(dialogData.jcsj) }}
            </el-descriptions-item>
            <el-descriptions-item label="当月水质"
              >{{ dialogData.szlb }}
            </el-descriptions-item>
            <el-descriptions-item label="溶解氧"
              >{{ dialogData.rjy }}
            </el-descriptions-item>
            <el-descriptions-item label="高猛酸盐指数"
              >{{ dialogData.gmsyzs }}
            </el-descriptions-item>
            <el-descriptions-item label="铜"
              >{{ dialogData.tong }}
            </el-descriptions-item>
            <el-descriptions-item label="锌"
              >{{ dialogData.xin }}
            </el-descriptions-item>
            <el-descriptions-item label="铅"
              >{{ dialogData.qian }}
            </el-descriptions-item>
            <el-descriptions-item label="镉"
              >{{ dialogData.ge }}
            </el-descriptions-item>
            <el-descriptions-item label="挥发酚"
              >{{ dialogData.hff }}
            </el-descriptions-item>
            <el-descriptions-item label="总磷"
              >{{ dialogData.zl }}
            </el-descriptions-item>
            <el-descriptions-item label="阴离子表面活性剂"
              >{{ dialogData.ylzbmhxj }}
            </el-descriptions-item>
            <el-descriptions-item label="化学需氧量"
              >{{ dialogData.cod }}
            </el-descriptions-item>
            <el-descriptions-item label="氨氮"
              >{{ dialogData.nh3n }}
            </el-descriptions-item>
            <el-descriptions-item label="总氮"
              >{{ dialogData.zd }}
            </el-descriptions-item>
            <el-descriptions-item label="氰化物"
              >{{ dialogData.qhw }}
            </el-descriptions-item>
            <el-descriptions-item label="铬（六价）"
              >{{ dialogData.luo }}
            </el-descriptions-item>
            <el-descriptions-item label="砷"
              >{{ dialogData.shen }}
            </el-descriptions-item>
            <el-descriptions-item label="硒"
              >{{ dialogData.xi }}
            </el-descriptions-item>
            <el-descriptions-item label="汞"
              >{{ dialogData.gong }}
            </el-descriptions-item>
            <el-descriptions-item label="硫化物"
              >{{ dialogData.lhw }}
            </el-descriptions-item>
            <el-descriptions-item label="生化需氧量"
              >{{ dialogData.bod5 }}
            </el-descriptions-item>
            <el-descriptions-item label="氟化物"
              >{{ dialogData.fhw }}
            </el-descriptions-item>

            <el-descriptions-item label="粪大肠菌群"
              >{{ dialogData.fdcjq }}
            </el-descriptions-item>
            <el-descriptions-item label="石油类"
              >{{ dialogData.syl }}
            </el-descriptions-item>
            <el-descriptions-item label="水温"
              >{{ dialogData.sw }}
            </el-descriptions-item>
            <el-descriptions-item label="PH值"
              >{{ dialogData.ph }}
            </el-descriptions-item>

            <!-- 其他描述项 -->
            <!-- <template>
              <el-descriptions-item> </el-descriptions-item>
            </template> -->
          </el-descriptions>
          <!-- 按钮区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button type="info"> 查看文件 </el-button>
            <el-button
              type="danger"
              v-if="
                dialogData.shenhezt !== '03' && dialogData.shenhezt !== '04'
              "
              @click="confirmReject"
            >
              回退
            </el-button>
            <!-- 如果状态不是 '3'，则显示审核通过按钮 -->
            <el-button
              type="primary"
              v-if="
                dialogData.shenhezt !== '03' && dialogData.shenhezt !== '04'
              "
              @click="handleApprove"
            >
              审核通过
            </el-button>
          </span>
        </el-dialog>
      </div>
      <div class="bottom">
        <el-pagination
          :current-page="currentPage"
          background
          layout="total, prev, pager, next, jumper"
          :total="totalItems"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-main>
  </div>
</template>

<script>
import { MessageBox } from "element-ui";
import config from "@/config/config.js";
export default {
  name: "DataAudit",
  data() {
    return {
      selectedStatus: "03", // 用户选择的数据状态
      selectedXzqh: "150602", // 默认选中150602
      config: config,
      dialogVisible: false,
      tableheight: 300,
      isEditable: true,
      filteredData: [], // 根据查询条件过滤后的数据
      queryForm: {
        keyword: "", // 查询关键字
        yearMonth: "", // 年月信息
      },
      tableData: [], // 数据
      dialogData: [], //根据id拿到的数据

      paginatedData: [], // 当前页的数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数据量
      totalItems: 0, // 总项目数

      // 初始化按钮可点击状态

      // selection: [], // 用于存储用户选择的项目
      selectedIds: [], // 存储选择的项目的 ID
      xzqhOptions: [
        { xzqhname: "东胜区", xzqhcode: "150602" },
        { xzqhname: "康巴什区", xzqhcode: "150601" },
        { xzqhname: "达拉特旗", xzqhcode: "150621" },
        { xzqhname: "准格尔旗", xzqhcode: "150622" },
        { xzqhname: "鄂托克前旗", xzqhcode: "150623" },
        { xzqhname: "鄂托克旗", xzqhcode: "150624" },
        { xzqhname: "杭锦旗", xzqhcode: "150625" },
        { xzqhname: "乌审旗", xzqhcode: "150626" },
        { xzqhname: "伊金霍洛旗", xzqhcode: "150627" },
      ],
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize);
    },
    currentDate() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      return `${year}-${month < 10 ? "0" + month : month}`;
    },
  },
  created() {
    const height = window.innerHeight - 200;
    this.tableheight = height;
    // this.fetchData();
    // this.getData();
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    this.queryForm.yearMonth = `${year}-${month < 10 ? "0" + month : month}`;
    this.getUser();
  },
  methods: {
    fetchDataByStatus() {

   this.fetchData(this.selectedXzqh, this.queryForm.yearMonth);
},
    onDateChange(date) {
      if (!date) return; // 如果日期为空，则不发送请求
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      this.queryForm.yearMonth = `${year}-${month < 10 ? "0" + month : month}`;
      // this.getUser(); // 调用获取数据的方法
      this.fetchData(this.selectedXzqh, this.queryForm.yearMonth);
    },
    handleSelectionChange(selection) {
      this.selectedIds = [];
      this.selectedIds = selection.map((item) => item.dmszjcid);
    },
    onXzqhChange() {
      // 在这里根据选中的旗区请求数据
      const selectedXzqh = this.selectedXzqh;
      const yearMonth = this.queryForm.yearMonth;
      // 判断用户是否已经选择了时间
      if (!yearMonth) {
        // 如果用户未选择时间，则将地区重置为东胜区
        this.selectedXzqh = "150602"; // 默认选中东胜区
        // 触发旗区选项变化事件
        console.log("选中的旗区变化了");
        return;
      }
      // 根据选中的旗区和年月进行数据请求
      this.fetchData(selectedXzqh, yearMonth);
    },
    getUser() {
      this.$api
        .getUser()
        .then((response) => {
          if (response.data.code == 906) {
            // return  alert('token已过期')
            this.$router.push(`/login`);
          }

          console.log("录入的行政区划", response);
          const userAreaCode = response.data.data.areacode;
          const yearMonth = this.queryForm.yearMonth; // 获取选择的年月
          console.log("年月", yearMonth);

          // 如果用户未选择时间，则按照之前的逻辑处理
          switch (userAreaCode) {
            case "1506":
              this.xzqhOptions = [
                { xzqhname: "东胜区", xzqhcode: "150602" },
                { xzqhname: "康巴什区", xzqhcode: "150601" },
                { xzqhname: "达拉特旗", xzqhcode: "150621" },
                { xzqhname: "准格尔旗", xzqhcode: "150622" },
                { xzqhname: "鄂托克前旗", xzqhcode: "150623" },
                { xzqhname: "鄂托克旗", xzqhcode: "150624" },
                { xzqhname: "杭锦旗", xzqhcode: "150625" },
                { xzqhname: "乌审旗", xzqhcode: "150626" },
                { xzqhname: "伊金霍洛旗", xzqhcode: "150627" },
              ];
              this.selectedXzqh = "150602"; // 默认选中东胜区
              break;
            default:
              let selectedOption = this.xzqhOptions.find(
                (option) => option.xzqhcode === userAreaCode
              );
              if (selectedOption) {
                this.selectedXzqh = selectedOption.xzqhcode; // 默认选中用户所在地区的旗区代码
                this.xzqhOptions = [selectedOption]; // 只保留用户所在地区的选项
              }
              break;
          }

          this.fetchData(this.selectedXzqh, yearMonth); // 传递年月信息// 示例用户区域编码
          // this.fetchData(userAreaCode)
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },
    fetchData(userAreaCode, yearMonth) {
      // 调用 user.js 中的 getData 方法
      this.$api
        .getNDmSzjcInfo(userAreaCode, yearMonth)
        .then((response) => {
          console.log("拿到的数据", response);
          this.tableData = response.data.data;

          this.tableData.forEach((item) => {
            // 获取状态
            const status = item.shenhezt;

            // 根据状态进行处理
            switch (status) {
              case "100":
                item.shenhezt = "01";
                break;
              case "101":
              case "102":
              case "104":
                item.shenhezt = "02";
                break;
              case "103":
                item.shenhezt = "04";
                break;
              case "111":
                item.shenhezt = "03";
                break;
              default:
                break;
            }
          });
          const filteredData = this.tableData.filter(
            (item) => item.shenhezt === this.selectedStatus
          );

          // 更新表格数据
          this.tableData = filteredData;

          this.totalItems = this.tableData.length;
          this.paginateData();
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },

    // 查询
    onSearch() {
      console.log("查询");
      const keyword = this.queryForm.keyword.trim().toLowerCase();
      console.log("遍历的数据", this.tableData);

      this.filteredData = this.tableData.filter((item) =>
        String(item.dmmc).toLowerCase().includes(keyword)
      );

      console.log(this.filteredData);

      this.paginatedData = this.filteredData;
      this.totalItems = this.filteredData.length;
    },

    // 点击审核
    handleAudit(id) {
      this.$api.getNDmSzjcDataById(id).then((response) => {
        console.log("id数据", response.data.data);
        this.dialogData = response.data.data;
        this.dialogVisible = true;
      });
    },
    // 点击查看
    handleView(id) {
      console.log(id);

      this.$api.getNDmSzjcDataById(id).then((response) => {
        console.log("id数据", response.data.data);
        this.dialogData = response.data.data;
        this.dialogVisible = true;
      });
    },

    // 切换分页
    paginateData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedData = this.tableData.slice(start, end);
    },

    handleCurrentChange(val) {
      // 当用户切换分页时触发
      this.currentPage = val;
      this.paginateData();
    },

    // 将时间戳转换为格式化的日期字符串
    formatTimestamp(timestamp) {
      return new Date(timestamp).toLocaleDateString();
    },
    // 审核通过
    handleApprove() {
      MessageBox.confirm("确定要审核通过吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮
          // 在这里调用审核通过的接口，并传递相应的数据项 ID
          const id = this.dialogData.id;
          this.dialogData.shenhezt = "03";
          // 假设 dialogData 中包含数据项的 ID
          const shenhezt = this.dialogData.shenhezt; // 假设 dialogData 中包含数据项的 ID
          this.$api
            .shenheNDmSzjcData(id, shenhezt)
            .then((response) => {
              console.log("审核通过成功", response);

              // 处理审核通过成功的逻辑
              this.$message.success("审核通过成功");
              console.log("关闭框");
              this.dialogVisible = false; // 关闭弹出框
              this.getUser();
            })
            .catch((error) => {
              // 处理审核通过失败的逻辑
              console.error("审核通过失败", error);
              // 可以在这里做一些提示或者其他处理
            });
        })
        .catch(() => {
          // 用户点击了取消按钮
          // 在这里可以不做任何处理，或者做一些额外的操作
        });
    },
    // 审核未通过
    confirmReject() {
      MessageBox.confirm("确定要回退吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮
          // 在这里调用审核通过的接口，并传递相应的数据项 ID
          const id = this.dialogData.id;
          this.dialogData.shenhezt = "04";
          // 假设 dialogData 中包含数据项的 ID
          const shenhezt = this.dialogData.shenhezt; // 假设 dialogData 中包含数据项的 ID
          this.$api
            .shenheNDmSzjcData(id, shenhezt)
            .then((response) => {
              console.log("回退成功", response);

              // 处理审核通过成功的逻辑
              this.$message.success("回退成功");
              this.dialogVisible = false; // 关闭弹出框
              console.log("关闭框");
              this.getUser();
            })
            .catch((error) => {
              // 处理审核通过失败的逻辑
              console.error("回退失败", error);
              // 可以在这里做一些提示或者其他处理
            });
        })
        .catch(() => {
          // 用户点击了取消按钮
          // 在这里可以不做任何处理，或者做一些额外的操作
        });
    },
    // 一键审核
    handleOneKeyAudit() {
      MessageBox.confirm("确定要将这些审核通过吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮
          // 在这里调用审核通过的接口，并传递相应的数据项 ID

          this.dialogData.shenhezt = "03";
          // 假设 dialogData 中包含数据项的 ID
          const shenhezt = this.dialogData.shenhezt;
          console.log("id", this.selectedIds); // 假设 dialogData 中包含数据项的 ID
          this.$api
            .batshenheNDmSzjcData(this.selectedIds, shenhezt) // 假设调用的接口名为 oneKeyAudit
            .then((response) => {
              // 处理一键审核成功的逻辑
              console.log("批量审核返回的数据", response);
              this.$message.success("一键审核成功");
              this.getUser(); // 刷新数据
            })
            .catch((error) => {
              // 处理一键审核失败的逻辑
              console.error("一键审核失败", error);
              this.$message.error("一键审核失败");
            });
        })
        .catch(() => {
          // 用户点击了取消按钮
          // 在这里可以不做任何处理，或者做一些额外的操作
        });
    },

    // 一键回退
    handleOneKeyRollback() {
      this.$api
        .batshenheNDmSzjcData() // 假设调用的接口名为 oneKeyRollback
        .then((response) => {
          // 处理一键回退成功的逻辑
          this.$message.success("一键回退成功");
          this.getUser(); // 刷新数据
        })
        .catch((error) => {
          // 处理一键回退失败的逻辑
          console.error("一键回退失败", error);
          this.$message.error("一键回退失败");
        });
    },
  },
};
</script>

<style scoped>
.el-main {
  color: #333;
  box-sizing: border-box;
}

.top {
  background-color: rgb(232, 232, 232);
  border-radius: 2px;
  padding-left: 20px;
  padding-top: 8px;
  padding-bottom: 7px;
  overflow: hidden;
}
.center {
  /* height: 400px; */
}
.el-form-item {
  margin-bottom: 2px;
  vertical-align: top;
  margin-right: 16px;
}
.bottom {
  text-align: right;
}

.file-upload {
  margin-right: 20px; /* 调整按钮之间的间距 */
}
.file-upload input {
  display: none;
}

/* 添加样式来美化文件选择按钮 */
.file-upload {
  display: inline-block;
  cursor: pointer;
  padding: 10px 20px;
  background-color: #3498db;
  color: #fff;
  border-radius: 5px;
}

.dialog-content {
  display: flex;
  /* flex-direction: column; */
  /* align-items: center; */
  justify-content: center;
  height: 100%;
}
</style>
